package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.android.barcodescandemo.ScannerInerface;
import com.example.administrator.k3xiangmu.adapter.Saomiao2Adapter;
import com.example.administrator.k3xiangmu.adapter.SaomiaoAdapter;
import com.example.administrator.k3xiangmu.entity.Saomiao2Entity;
import com.example.administrator.k3xiangmu.entity.SaomiaoEntity;
import com.example.administrator.k3xiangmu.entity.XLH;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class Saomiao2Activity extends AppCompatActivity {
    private Toolbar toolbar;
    ListView lv;
    Saomiao2Adapter adapter;
    ProgressDialog dialog;
    ;
    List<Saomiao2Entity> list = new ArrayList<>();
    private String s = "";
    private String no = "";
    private String biller = "";
    private BroadcastReceiver mReceiver;
    private IntentFilter mFilter;
    ScannerInerface Controll = new ScannerInerface(this);
    List<XLH> xlhList = new ArrayList<>();
    private Button bt;
    private String fuser="";
    private String date="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saomiao2);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setTool();
        dialog = new ProgressDialog(this);
        //
        Controll.open();
        Controll.setOutputMode(1);//使用广播模式
        mFilter = new IntentFilter("android.intent.action.SCANRESULT");

        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // 此处获取扫描结果信息
                final String scanResult = intent.getStringExtra("value");
                String[] s = scanResult.split("\\[");
                if (s.length == 2) {
                    for (int i = 0; i < list.size(); i++) {

                        if (list.get(i).getId().equals(scanResult) && list.get(i).getStatus() == 2) {
                            Toast.makeText(Saomiao2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                            return;
                        } else if (list.get(i).getId().equals(s[0])) {
                            for (XLH x : xlhList) {
                                if (x.getFSN().equals(s[1])) {
                                    Toast.makeText(Saomiao2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                                    return;
                                }

                            }
                            int a = list.get(i).getYs();
                            if (list.get(i).getFInteger1() > a) {
                                list.get(i).setYs(++a);
                                if (list.get(i).getFInteger1() == a) {
                                    list.get(i).setStatus(2);
                                }
                            }
                            XLH x = new XLH();
                            x.setFID(list.get(i).getFid());
                            x.setFIndex(list.get(i).getFindex());
                            x.setFNumber(s[0]);
                            x.setFSN(s[1]);
                            x.setWehiz(list.get(i).getWeizhi());
                            x.setDate(list.get(i).getDate());
                            Log.i("asd", list.get(i).getWeizhi());
                            xlhList.add(x);
                            adapter.notifyDataSetChanged();
                            return;
                        }

                    }
                }


                Toast.makeText(Saomiao2Activity.this, "找不到该条码", Toast.LENGTH_LONG).show();

            }
        };
        //


        s = getIntent().getStringExtra("id");
        no = getIntent().getStringExtra("no");
        fuser=getIntent().getStringExtra("fuser");

        biller = getIntent().getStringExtra("biller");
        Log.i("ssss", no);
        Log.i("ssss", biller);
        lv = (ListView) findViewById(R.id.lv);
        adapter = new Saomiao2Adapter(list, this);
        lv.setAdapter(adapter);
        bt = (Button) findViewById(R.id.tj);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getStatus() == 0) {
                        Toast.makeText(Saomiao2Activity.this, "有单子未扫描", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                submit();
            }
        });
        getData();
    }

    private void submit() {
        dialog.show();
        UpdateTextTask4 updateTextTask = new UpdateTextTask4(Saomiao2Activity.this);
        updateTextTask.execute();
    }

    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("租赁单详情");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                String msg = "";
                switch (item.getItemId()) {
                    case R.id.action_sm:
                        msg += "Click edit";
                        break;

                }

                if (!msg.equals("")) {
                    Toast.makeText(Saomiao2Activity.this, msg, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(Saomiao2Activity.this, CaptureActivity.class);
                    startActivityForResult(intent, 111);

                }
                return true;

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 111) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String scanResult = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + scanResult, Toast.LENGTH_LONG).show();
                    //
                    String[] s = scanResult.split("\\[");
                    if (s.length == 2) {
                        for (int i = 0; i < list.size(); i++) {

                            if (list.get(i).getId().equals(scanResult) && list.get(i).getStatus() == 2) {
                                Toast.makeText(Saomiao2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                                return;
                            } else if (list.get(i).getId().equals(s[0])) {
                                for (XLH x : xlhList) {
                                    if (x.getFSN().equals(s[1])) {
                                        Toast.makeText(Saomiao2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();

                                        return;
                                    }

                                }
                                Log.i("asd", "+++++++++");
                                int a = list.get(i).getYs();
                                if (list.get(i).getFInteger1() > a) {
                                    list.get(i).setYs(++a);
                                    if (list.get(i).getFInteger1() == a) {
                                        list.get(i).setStatus(2);
                                    }
                                }
                                XLH x = new XLH();
                                x.setFID(list.get(i).getFid());
                                x.setFIndex(list.get(i).getFindex());
                                x.setFNumber(s[0]);
                                x.setFSN(s[1]);
                                x.setWehiz(list.get(i).getWeizhi());
                                Log.i("asd", list.get(i).getWeizhi()+"sss");
                                xlhList.add(x);
                                adapter.notifyDataSetChanged();
                                return;
                            }

                        }
                    }
                    //
//                    for (int i = 0; i < list.size(); i++) {
//
//                        if (list.get(i).getId().equals(result) && list.get(i).getStatus() == 2) {
//                            Toast.makeText(Saomiao2Activity.this, "该物料已扫描完毕", Toast.LENGTH_LONG).show();
//
//                            return;
//                        } else if (list.get(i).getId().equals(result)) {
//                            int a = list.get(i).getYs();
//                            if (list.get(i).getFInteger1() > a) {
//                                list.get(i).setYs(++a);
//                                if (list.get(i).getFInteger1() == a) {
//                                    list.get(i).setStatus(2);
//                                }
//                            }
//
//                            adapter.notifyDataSetChanged();
//                            return;
//                        }
//
//                    }
                    Toast.makeText(Saomiao2Activity.this, "找不到该条码", Toast.LENGTH_LONG).show();

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(Saomiao2Activity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void update() {
        UpdateTextTask3 updateTextTask = new UpdateTextTask3(this);
        updateTextTask.execute();
    }

    private void getData() {
        dialog.show();
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }

    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            adapter.notifyDataSetChanged();
            //     Log.i("ss", list.get(1).getId() + "+++++++++++++++");
            dialog.dismiss();
        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            Toast.makeText(Saomiao2Activity.this, "成功", Toast.LENGTH_LONG).show();
            finish();
            ;

        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {
            list.clear();
            String sql = "select a.* ,b.FName ,b.fnumber from t_BOS200000001Entry2 a inner join t_ICItem b on a.FBase2=b.FItemID where fid='" + s + "'";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                Saomiao2Entity entity = new Saomiao2Entity();
                entity.setFName(rs.getString("FName"));
                entity.setFInteger1(Integer.parseInt(rs.getString("Finteger")));
                entity.setId(rs.getString("fnumber"));
                entity.setWeizhi(rs.getString("ftext2"));
                Log.i("sss", rs.getString("fnumber"));
                entity.setFid(rs.getInt("FID"));
                entity.setFindex(rs.getInt("FIndex"));
                entity.setDate(rs.getDate("fdate3"));
                list.add(entity);


            }


            rs.close();
            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    public void testConnection3(Connection con) throws java.sql.SQLException {

        try {

            String sql = "update t_BOS200000001 set FMultiCheckStatus=16 where FID='" + s + "'";

            Statement stmt = con.createStatement();// 创建Statement
            stmt.executeUpdate(sql);


            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd");


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mFilter);
    }

    @Override
    protected void onPause() {
        this.unregisterReceiver(mReceiver);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mReceiver = null;
        mFilter = null;

        Controll.close();
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);//加载menu文件到布局
        return true;
    }

    class UpdateTextTask4 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask4(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection4(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            dialog.dismiss();
            Toast.makeText(Saomiao2Activity.this, "提交成功", Toast.LENGTH_LONG).show();
            finish();


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    public void testConnection4(Connection con) throws java.sql.SQLException {
        // CallableStatement callStmt = null;
        // Statement stmt2 =null;
        PreparedStatement pstmt = null;
        Statement statement3 = null;
        Statement pstmt2 = null;
        try {
            statement3 = con.createStatement();
            pstmt = con.prepareStatement("update t_BOS200000001 set fmulticheckstatus=16 where fbillno='" + no + "'");
            pstmt.execute();
            // pstmt.execute("update z_xlh_zulin set weizhi='"+no+"' where ");
            pstmt2 = con.createStatement();
            for (XLH x : xlhList) {

                String s = "INSERT INTO dbo.z_xlh_zulin( FID, FSN, FIndex, FNumber )VALUES  ( " + x.getFID() + ",  '" + x.getFSN() + "'," + x.getFIndex() + ", '" + x.getFNumber() + "' )";

                pstmt2.execute(s);
                String s2 = "INSERT INTO dbo.z_xlh_xq ( FSN, status)VALUES  ( '" + x.getFSN() + "','租赁' )";
                pstmt2.execute(s2);
                String s3 = "update z_xlh_zulin set weizhi='" + x.getWehiz() + "',fuser='"+fuser+"',fdate="+x.getDate()+" where fsn='" + x.getFSN() + "'";
                Log.i("qqq", s3 + "dddddddd");
                statement3.execute(s3);
            }
            // callStmt = con.prepareCall("{call [x_xlhqin] (?,?)}");
            //stmt2=con.createStatement();
//            callStmt.setString(1, no);
//            callStmt.setString(2, biller);
//
//
//            callStmt.execute();
//            callStmt.close();
            //callStmt.executeUpdate("update t_BOS200000001 set fmulticheckstatus=16 where fbillno="+no+"");
            // stmt2.executeUpdate("update t_BOS200000001 set fmulticheckstatus=16 where fbillno='"+no+"'");
            //Log.i("qqq",r+"++++++++++++");

        } catch (SQLException e) {
            Log.i("qqq", e.toString() + "++++++++++++");

        } finally {
            if (null != pstmt) {
                pstmt.close();
            }
            if (null != pstmt2) {
                pstmt2.close();
            }
            if (null != statement3) {
                statement3.close();
            }

//            if (null != callStmt) {
//                callStmt.close();
//            }
//            if(null != stmt2){
//                stmt2.close();
//            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }


}
